package com.jf.cloud.user.feign;

import cn.hutool.core.collection.CollUtil;
import com.jf.cloud.api.user.dto.ShopCustomerReqDTO;
import com.jf.cloud.api.user.feign.ShopCustomerFeignClient;

import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.user.model.ShopCustomer;
import com.jf.cloud.user.service.ShopCustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 店铺客户
 * @author: zsm
 * @date: 2023/1/15 16:44
 */
@RestController
public class ShopCustomerClientController implements ShopCustomerFeignClient {

    @Autowired
    private ShopCustomerService shopCustomerService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServerResponseEntity<Void> saveBatchByOrders(@RequestBody ShopCustomerReqDTO shopCustomerReqDTO) {
        List<Long> shopIds = shopCustomerReqDTO.getShopIds();
        Long userId = shopCustomerReqDTO.getUserId();
        List<ShopCustomer> list = new ArrayList<>();
        List<ShopCustomer> shopCustomers = shopCustomerService.listByUserId(userId);
        List<Long> shopIdList = shopCustomers.stream().map(ShopCustomer::getShopId).collect(Collectors.toList());
        for(Long shopId : shopIds){
            if(shopIdList.contains(shopId)){
                continue;
            }
            ShopCustomer shopCustomer = new ShopCustomer();
            shopCustomer.setShopId(shopId);
            shopCustomer.setUserId(userId);
            list.add(shopCustomer);
        }
        if (CollUtil.isNotEmpty(list)) {
            shopCustomerService.saveBatch(list);
        }
        return ServerResponseEntity.success();
    }
}
